{% extends 'bootstrap/base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Kung Fu Realm{%endblock %}
{% block head %}
<head>
<meta charset="utf-8">
<title>Hi Hi 聊天室</title>
<link rel="shortcut icon" href="{{ url_for('static',filename='chat/images/hihi.jpg')}}">
<link rel="icon" href="{{ url_for('static',filename='chat/images/hihi.jpg')}}" type="image/x-icon">
<link  id="css" type="text/css" rel="stylesheet" href="/static/chat/css/style.css">
    <!--<link type="text/css" rel="stylesheet" href="/static/chat/css/style-contorl.css">-->
<script type="text/javascript" src="{{ url_for('static', filename='chat/js/jquery.min.js') }}"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.10.0/js/md5.min.js"></script>　
</head>
{% endblock %}
{% block content %}
<body>
<h1>ROOM: {{ rname }}</h1>
<div class="chatbox">
  <div class="chat_top fn-clear">
      <div class="uinfo fn-clear"  style="float: left;">
          <div class="uface">
              <h1 style="color: #7777"><a href="/">Home</a>
              </h1>
          </div>
      </div>
    <div class="uinfo fn-clear">
    {% if current_user.is_authenticated %}
      <div class="uface"><img src="{{ current_user.gravatar(size=40) }}" width="40" height="40"  alt=""/></div>
    {% else %}
      <div class="uface"><img src="{{ url_for('static', filename='chat/images/hi.jpg')}}" width="40" height="40"  alt=""/></div>
    {% endif %}
      <div class="uname">
          {% if current_user.is_authenticated %}
        {{ current_user.username }}
          {% else %}
          游客
          {% endif %}
          <i class="fontico down"></i>
          <ul class="managerbox">
            {% if current_user.is_authenticated %}
            <li><a href="{{ url_for('main.room_user_list', rname=rname) }}" target="_blank"><i class="fontico lock"></i>管理用户</a></li>
            <li><span id="control" onclick="setBg()">&ensp;<i class="fontico lock"></i>&ensp;&ensp;切换背景</span></li>
          <li><a href="{{ url_for('main.logout', rname=rname) }}"><i class="fontico logout"></i>退出登陆</a></li>
            <li><a href="{{ url_for('main.logout') }}"><i class="fontico lock"></i>退出房间</a></li>
            {% else %}
          <li><a href="{{ url_for('main.login') }}"><i class="fontico logout"></i>登录</a></li>
            {% endif %}
          </ul>
      </div>
    </div>
  </div>
  <div class="chat_message fn-clear">
    <div class="chat_left">
      <div class="message_box" id="message_box">
        <div class="msg_item fn-clear">
          <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>
          <div class="item_right">
            <div class="msg own"><img src="{{ url_for('static', filename='chat/images/hihi.jpg')}}" width="400" height="400"  alt=""/></div>
            <div class="name_time">小黄鸭 </div>
          </div>
        </div>
          {% if current_user.is_authenticated %}
        <div class="msg_item fn-clear">
          <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>
          <div class="item_right">
            <div class="msg">Welcome to Hihi Chat Room. 欢迎来到 Hihi 聊天室。 </div>
            <div class="name_time">小黄鸭 </div>
          </div>
        </div>
          {% if msg_list %}
          {% for i in msg_list %}
          {% if i[0]['username'] == current_user.username %}
         <div class="msg_item fn-clear">
          <div class="uface"><img src="{{ current_user.gravatar(name=i[0]['username'], size=40) }}" width="40" height="40"  alt=""/></div>
          <div class="item_right">
            <div class="msg">{{ i[0]['msg'] }}</div>
            <div class="name_time">你 · {{ i[1] }} </div>
          </div>
         </div>
          {% else %}
          <div class="msg_item fn-clear">
          <div class="uface"><img src="{{ current_user.gravatar(name=i[0]['username'], size=40) }}" width="40" height="40"  alt=""/></div>
          <div class="item_right">
            <div class="msg">{{ i[0]['msg'] }}</div>
            <div class="name_time">{{ i[0]['username'] }} · {{ i[1] }} </div>
          </div>
         </div>
          {% endif %}
          {% endfor %}
          {% endif %}
          {% else %}
          <div class="msg_item fn-clear">
          <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>
          <div class="item_right">
            <div class="msg">您还没有登陆，先和小黄鸭聊聊吧。 </div>
            <div class="name_time">小黄鸭 </div>
          </div>
        </div>
          {% endif %}
      </div>
      <div class="write_box">
      {% if current_user.is_authenticated %}
        <textarea id="message" name="message" class="write_area" placeholder="和室友说点啥吧..."></textarea>
        <input type="hidden" name="fromname" id="fromname" value="{{ current_user.username }}" />
      {% else %}
      <textarea id="message_not" name="message" class="write_area" placeholder="还没登陆，还小黄鸭说点啥吧..."></textarea>
      {% endif %}

        <input type="hidden" name="to_uid" id="to_uid" value="0">
        <div class="facebox fn-clear">
          <div class="expression"></div>
          <div class="chat_type" id="chat_type">群聊</div>
            {% if current_user.is_authenticated %}
          <button name="login" class="sub_but" id="sub_but_login">提 交</button>
            {% else %}
          <button name="logout" class="sub_but" id="sub_but">提 交</button>
            {% endif %}
        </div>
      </div>
    </div>
      <div class="chat_pleft">
          <ul class="puser_list" title="" id="pchat">
              <li class="fn-clear selected"><em id="pall">所有私聊</em></li>
              <li class="fn-clear" data-id="112" id="private"><span></span><em>暂时没有任何私聊</em></li>
          </ul>
      </div>
    <div class="chat_right">
      <ul class="user_list" title="">
        <li class="fn-clear selected"><em id="all">所有用户</em></li>
        <li class="fn-clear" data-id="1"><span><img src="{{ url_for('static', filename='chat/images/hi.jpg')}}" width="30" height="30"  alt=""/></span><em>小HI</em><small class="online" title="在线"></small></li>
        <li class="fn-clear" data-id="2"><span><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="30" height="30"  alt=""/></span><em>小黄鸭</em><small class="online" title="在线"></small></li>
          {% if current_user.is_authenticated %}
          {% for i in user_list %}
          {% if i == current_user.username %}
           {% if i in b_user_list %}
        <li class="fn-clear" data-id="3"><span><img src="{{ current_user.gravatar(size=40) }}" width="30" height="30"  alt=""/></span>
            <em>{{ i }}</em><small class="offline" title="禁言"></small></li>
          {% else %}
        <li class="fn-clear" data-id="3"><span><img src="{{ current_user.gravatar(size=40) }}" width="30" height="30"  alt=""/></span>
            <em>{{ i }}</em><small class="online" title="在线"></small></li>
          {% endif %}
          {% else %}
          {% if i in b_user_list %}
         <li class="fn-clear" data-id="3"><span><img src="{{ current_user.gravatar(name=i, size=40) }}" width="30" height="30"  alt=""/></span>
            <em>{{ i }}</em>
              <small class="offline" title="禁言">
              </small>
         </li>
          {% else %}
         <li class="fn-clear" data-id="3"><span><img src="{{ current_user.gravatar(name=i, size=40) }}" width="30" height="30"  alt=""/></span>
            <em>{{ i }}</em>
              <small class="online" title="在线">
              </small>
         </li>
          {% endif %}
          {% endif %}
          {% endfor %}
          {% else %}
          <li class="fn-clear" data-id="3">
              <span>
                  <img src="{{ g }}" width="30" height="30"  alt=""/>
              </span>
            <em>游客</em>
              <small class="online" title="在线">
              </small>
          </li>
          {% endif %}
      </ul>
    </div>
  </div>
</div>
<script type="text/javascript">
function setBg() {
    var host = window.location.host;
    var protocol = window.location.protocol;
    var css_href = document.getElementById('css').href;
    var css_url = protocol + "//" + host + "/static/chat/css/style-contorl.css";
    console.log(css_url);
    //console.log("css url", css_href);
    if(css_href == css_url){
        document.getElementById('css').href='/static/chat/css/style.css'
    }else{
        document.getElementById('css').href='/static/chat/css/style-contorl.css'
    }
    }

$(document).ready(function(e) {
    // 定时更新私聊列表
    setInterval(function() {
        $.get("http://127.0.0.1:8889/api/pchat/" + "{{ current_user.username }}",//GET请求的url地址
        function(data,status){
            var roomlist = JSON.parse(data);
            // var private_html1 = '<li class="fn-clear" id="private"><p>';
            // var private_html2 = '</p></li>';
            var li_html = '<li class="fn-clear selected"><em id="pall">所有私聊</em></li>';
            for (var i =0; i<roomlist.length; i++) {
                li_html += roomlist[i];
                //$("#private").html(private_html1 + roomlist[i] + private_html2);//更新列表内容
            }
            console.log(li_html);
            $("#pchat").html(li_html);//更新列表内容
          });
        }, 5000); //定时刷新界面（0.5秒）

	$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$('.uname').hover(
	    function(){
		    $('.managerbox').stop(true, true).slideDown(100);
	    },
		function(){
		    $('.managerbox').stop(true, true).slideUp(100);
		}
	);

	// 用户列表操作
	var fromname = $('#fromname').val();
	var to_uid   = 0; // 默认为0,表示发送给所有用户
	var to_uname = '';
	$('.user_list > li').dblclick(function(){
		to_uname = $(this).find('em').text();
		to_uid   = $(this).attr('data-id');
        var redirect_url = 'http://' + document.domain + ':' + location.port + '/privatechat/?to=' + to_uname;
        // var room_url = 'http://' + document.domain + ':' + location.port + '/joinroom/';
		if(to_uname == fromname){
		    alert('您不能和自己聊天!');
			return false;
		}
		if(to_uname == '所有用户'){
		    $("#toname").val('');
			$('#chat_type').text('群聊');
		}else{
		    // 新开窗口私聊
		    window.open(redirect_url);
		    // 在当前页面私聊
		    // $("#toname").val(to_uid);
			// $('#chat_type').text('您正和 ' + to_uname + ' 聊天');
		}
		$(this).addClass('selected').siblings().removeClass('selected');
		// 在当前页面私聊
	    // $('#message').focus().attr("placeholder", "您对"+to_uname+"说：");
	    // $('#message_not').focus().attr("placeholder", "您对"+to_uname+"说：");
	});

	/* 右键菜单 */
	/*
	$('.user_list > li').mousedown(function(e){
	    if (3 == e.which){
	        alert('thisis ');
	    }
	});
	*/

    /*用户未登陆的用户点击提交按钮发送消息按钮*/
	$('#sub_but').click(function(event){
	    sendMessage(event, fromname, to_uid, to_uname);
	});
	/*用户登陆的用户点击提交按钮发送消息按钮*/
	$('#sub_but_login').click(function(event){
	    sendMessageLogin(event, fromname, to_uid, to_uname);
	});

	/*用户未登陆的用户，按下按钮或键盘按键*/
	$("#message_not").keydown(function(event){
		var e = window.event || event;
        var k = e.keyCode || e.which || e.charCode;
		//按下ctrl+enter发送消息
		if((event.ctrlKey && (k == 13 || k == 10) )){
			sendMessage(event, fromname, to_uid, to_uname);
		}
	});
	/*用于登陆的用户*/
		$("#message").keydown(function(event){
		var e = window.event || event;
        var k = e.keyCode || e.which || e.charCode;
		//按下ctrl+enter发送消息
		if((event.ctrlKey && (k == 13 || k == 10) )){
			sendMessageLogin(event, fromname, to_uid, to_uname);
		}
	});
});

function pchat(id){
        var to_user = id;
        var redirect_url = 'http://' + document.domain + ':' + location.port + '/privatechat/?to=' + to_user;
        window.open(redirect_url);
    }

function sendMessage(event, from_name, to_uid, to_uname){
    var msg = $("#message_not").val();
	var myDate = new Date();
	var myTime = myDate.toLocaleTimeString();
	var itTime = myDate.toLocaleString();
	//var iTime = myDate.toDateString();
	var htmlData =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="{{ url_for('static', filename='chat/images/hi.jpg')}}" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg own">' + msg + '</div>'
			       + '     <div class="name_time">' + from_name + ' · ' + itTime +'</div>'
			       + '   </div>'
			       + '</div>';
	$("#message_box").append(htmlData);
	$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$("#message_not").val('');
	setTimeout(function(){sendToServernoLogin(from_name, msg)}, 1000); //延时调用
}
function sendToServernoLogin(name, msg){
    var xmlhttp = new XMLHttpRequest();
	var myDate = new Date();
	var myRname = "{{ rname }}";
	//var myTime = myDate.toLocaleTimeString();
    var myTime = myDate.toLocaleString();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            myObj = xmlhttp.responseText;
            var htmlData2 =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg">' + myObj + '</div>'
			       + '     <div class="name_time">' + '小黄鸭' + ' · ' + myTime +'</div>'
			       + '   </div>'
			       + '</div>';
            $("#message_box").append(htmlData2);
            $('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
        }
    }
    xmlhttp.open("POST", "/api/sendchat/" + msg , true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.send("rname=" + myRname);

};

function sendMessageLogin(event, from_name, to_uid, to_uname){
    var msg = $("#message").val();
	var myDate = new Date();
	var myTime = myDate.toLocaleTimeString();
	var itTime = myDate.toLocaleString();
	//var iTime = myDate.toDateString();
	var htmlData =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface">{% if current_user.is_authenticated %}<img src="{{ current_user.gravatar(size=40) }}" width="40" height="40"  alt=""/>{% endif %}</div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg own">' + msg + '</div>'
			       + '     <div class="name_time">' + from_name + ' · ' + itTime +'</div>'
			       + '   </div>'
			       + '</div>';
	//$("#message_box").append(htmlData);
	//$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$("#message").val('');
	setTimeout(function(){sendToServer(from_name, msg)}, 1000); //延时调用
}

function sendToServer(name, msg){
    var xmlhttp = new XMLHttpRequest();
	var myDate = new Date();
	var myRname = "{{ rname }}";
	//var myTime = myDate.toLocaleTimeString();
    var myTime = myDate.toLocaleString();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            myObj = xmlhttp.responseText;
            var htmlData2 =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg">' + "自动回复" + myObj + '</div>'
			       + '     <div class="name_time">' + '小黄鸭' + ' · ' + myTime +'</div>'
			       + '   </div>'
			       + '</div>';
            //$("#message_box").append(htmlData2);
            //$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);

               var jsondata = JSON.parse(myObj);
               if ( jsondata.code == 201 || jsondata.code == 403) {
                   var htmlData3 =   '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="{{ url_for('static', filename='chat/images/duck.jpg')}}" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg">' + "自动回复: " + jsondata.msg + '</div>'
			       + '     <div class="name_time">' + '小黄鸭' + ' · ' + myTime +'</div>'
			       + '   </div>'
			       + '</div>';
			   $("#message_box").append(htmlData3);
               $('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
               }
        }
    };
    xmlhttp.open("POST", "/api/sendchat/" + msg , true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.send("rname=" + myRname);

}

//websocket
var websocket_url = 'ws://' + document.domain + ':' + location.port + '/testnamespace';
var socket = io.connect(websocket_url);
//发送消息
//console.log({{rname}});
socket.emit('request_for_response',{'param':'{{rname}}'});


//监听回复的消息
socket.on('response',function(data){
    var myDate = new Date();
    var myTime = myDate.toLocaleString();
    var msg = data.msg;
    var username = data.username;
    var currentuser = '{{ current_user.username }}';
    var hash = md5(username + "@hihichat.com");
    if ( currentuser == username )
    {
    username = '你';
    };
    var htmlData2 =
                    '<div class="msg_item fn-clear">'
                   + '   <div class="uface"><img src="http://www.gravatar.com/avatar/' + hash + '?s=40&d=identicon&r=g" width="40" height="40"  alt=""/></div>'
			       + '   <div class="item_right">'
			       + '     <div class="msg">' + msg + '</div>'
			       + '     <div class="name_time">' + username + ' · ' + myTime +'</div>'
			       + '   </div>'
			       + '</div>';
    $("#message_box").append(htmlData2);
    $('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
});

</script>
</body>
{% endblock %}
